import 'package:flutter/material.dart';

main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Flutter Demo",
      debugShowCheckedModeBanner: false,
      home: JKHomePage(),
    );
  }
}

class JKHomePage extends StatefulWidget {
  @override
  _JKHomePageState createState() => _JKHomePageState();
}

class _JKHomePageState extends State<JKHomePage> {
  ScrollController controller = ScrollController(initialScrollOffset: 100);
  // 是否显示置顶按钮
  bool isShowFloatingBtn = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    controller.addListener(() {
      print("监听到滚动：${controller.offset}");
      setState(() {
        isShowFloatingBtn = controller.offset > 200;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    /**
     * 两种监听方式
     * 第一种：controller
     *   优点：1、可以设置默认值offset
     *        2、监听滚动，也可以监听滚动的位置
     *   缺点：不可以监听滚动的开始位置和结束位置
     * 第二种：NotificationListener
     */
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "标题",
          style: TextStyle(
              fontSize: 22,
              color: Colors.yellow
          ),
        ),
      ),
      body: ListView.builder(
          controller: controller,
          itemCount: 30,
          itemBuilder: (BuildContext ctx, int index) {
            return ListTile(
              title: Text("联系人$index"),
              leading: Icon(Icons.people),
            );
          }
      ),
      floatingActionButton: isShowFloatingBtn ? FloatingActionButton(
        child: Icon(Icons.arrow_upward),
        onPressed: () {
          controller.animateTo(0, duration: Duration(seconds: 1), curve: Curves.easeIn);
        },
      ) : null,
    );
  }
}